package DAO;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import POJO.AreaCurso;

public class AreaCursoDao 
{
	Connection c;
	
	public AreaCursoDao()
	{
		GenericDao gDao = new GenericDao();
		c = gDao.getConnection();
	}
	
	public void CadastrarCurso(AreaCurso aC) throws SQLException
	{
		String sql = "INSERT INTO AreaCurso (nomeCurso) VALUES (?)";
		PreparedStatement ps = c.prepareStatement(sql);
		ps.setString(1, aC.getNomeCurso());
		ps.execute();
		ps.close();
	}
	
	public void AlterarCurso(AreaCurso aC) throws SQLException
	{
		String sql = "UPDATE AreaCurso SET nomeCurso = ? WHERE codCurso = ?";
		PreparedStatement ps = c.prepareStatement(sql);
		ps.setString(1, aC.getNomeCurso());
		ps.setInt(2, aC.getCodCurso());
		ps.execute();
		ps.close();
	}
	
	public void DeletaCurso(AreaCurso aC) throws SQLException
	{
		String sql = "DELETE AreaCurso WHERE codCurso = ?";
		PreparedStatement ps = c.prepareStatement(sql);
		ps.setInt(1, aC.getCodCurso());
		ps.execute();
		ps.close();
	}
	
	public int ProximoCodigo() throws SQLException
	{
		int codigo = 1;
		String sql = "SELECT MAX(codCurso + 1) AS codCurso FROM AreaCurso";
		PreparedStatement ps = c.prepareStatement(sql);
		ResultSet rs = ps.executeQuery();
		if(rs.next())
		{
			codigo = rs.getInt("codCurso");
		}
		rs.close();
		ps.close();
		return codigo;
	}
	
	public AreaCurso consultaCurso (AreaCurso aC) throws SQLException
	{
		AreaCurso areaC = new AreaCurso();
		String sql = "SELECT codCurso, nomeCurso FROM AreaCurso WHERE codCurso = ?";
		PreparedStatement ps = c.prepareStatement(sql);
		ps.setInt(1, aC.getCodCurso());
		ResultSet rs = ps.executeQuery();
		if(rs.next())
		{
			areaC.setCodCurso(rs.getInt("codCurso"));
			areaC.setNomeCurso(rs.getString("nomeCurso"));
		}
		rs.close();
		ps.close();
		return areaC;
	}
	
	public List<AreaCurso> listaCursos() throws SQLException
	{
		List<AreaCurso> listaCursos = new ArrayList<AreaCurso>();
		String sql = "SELECT * FROM AreaCurso ORDER BY nomeCurso";
		PreparedStatement ps = c.prepareStatement(sql);
		ResultSet rs = ps.executeQuery();
		while(rs.next())
		{
			AreaCurso aC = new AreaCurso();
			aC.setCodCurso(rs.getInt("codCurso"));
			aC.setNomeCurso(rs.getString("nomeCurso"));
			listaCursos.add(aC);
		}
		rs.close();
		ps.close();
		return listaCursos;
	}
}